package com.hy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.common.base.RespResult;
import com.hy.common.base.RespResultCode;
import com.hy.common.consts.CommonConst;
import com.hy.common.consts.ExcelConstants;
import com.hy.common.consts.RedisConst;
import com.hy.common.consts.StateConst;
import com.hy.common.exception.BusinessException;
import com.hy.common.utils.*;
import com.hy.entity.dto.*;
import com.hy.entity.pojo.*;
import com.hy.entity.vo.*;
import com.hy.mapper.*;
import com.hy.service.HyCheckService;
import com.hy.service.HyPropertyService;
import com.hy.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class HyCheckServiceImpl implements HyCheckService {


    @Resource
    private ErrorProMapper errorProMapper;
    @Resource
    private HyUserMapper userMapper;
    @Resource
    private HyPlaceMapper placeMapper;
    @Resource
    private HyCheckMapper hyCheckMapper;
    @Resource
    private HyCheckTaskMapper hyCheckTaskMapper;
    @Resource
    private HyCheckDetailMapper hyCheckDetailMapper;

    @Resource
    private HyDepartmentMapper departmentMapper;
    @Resource
    private  HyPropertyService propertyService;

    @Resource
    private  HyPropertySortMapper sortMapper;
    @Resource
    private  HyPropertyMapper propertyMapper;
    @Resource
    private SysUserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    private Map<Integer,Function<ErrorPro,RespResult>> stateMap=new HashMap<>();
    private Map<Integer, Function<CheckSortDTO,RespResult>> sortTypeMap=new HashMap<>();
    private Map<Integer, Function<HyCheckDetail,RespResult>> detailAsync=new HashMap<>();

    @PostConstruct
    public void dispatcherInit(){
        sortTypeMap.put(StateConst.CHECK_SORT_BY_MANAGE_DEPT,sortDTO->this.sortByManageDept(sortDTO));
        sortTypeMap.put(StateConst.CHECK_SORT_BY_PROPERTY_SORT,sortDTO->this.sortByPropertySort(sortDTO));
        sortTypeMap.put(StateConst.CHECK_SORT_BY_MANAGE_USER,sortDTO->this.sortByManageUser(sortDTO));
        sortTypeMap.put(StateConst.CHECK_SORT_BY_PLACE,sortDTO->this.sortByPlace(sortDTO));
        stateMap.put(StateConst.ERROR_PROPERTY,errorPro -> this.panYing(errorPro));
        stateMap.put(StateConst.ERROR_LOSS_PROPERTY,errorPro -> this.panKui(errorPro));
        stateMap.put(StateConst.ERROR_BAD_WAIT_OUT,errorPro -> this.sunHui(errorPro));
        stateMap.put(StateConst.ERROR_NO_USE,errorPro -> this.xianZhi(errorPro));
        stateMap.put(StateConst.ERROR_MESSAGE_NO,errorPro -> this.xinXiBuYiZhi(errorPro));
        detailAsync.put(StateConst.LOSS_PROPERTY,detail->this.detailPanKui(detail));
        detailAsync.put(StateConst.BAD_WAIT_OUT,detail->this.detailSunHui(detail));
        detailAsync.put(StateConst.NO_USE,detail->this.detailXianZhi(detail));
        detailAsync.put(StateConst.HAVE_TAKEN_STOCK,detail->this.success(detail));
        detailAsync.put(StateConst.NO_TAKEN_STOCK,detail -> this.success(detail));
        detailAsync.put(StateConst.FIND_PROPERTY,detail -> this.success(detail));
        detailAsync.put(StateConst.Message_NO,detail -> this.detailMessageNo(detail));
    }
    public RespResult success(HyCheckDetail detail){
        return RespResult.success();

    }
    public RespResult detailMessageNo(HyCheckDetail detail){
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        ErrorPro errorPro=null;
        HyProperty property = propertyMapper.getPropertyByUnitAndRfid(detail.getUnitId(), detail.getPropertyRfid(),detail.getBelongCheckTaskId());
        try{
            errorPro = errorProMapper.selectOne(new LambdaQueryWrapper<ErrorPro>().and(wapper ->
                    wapper.eq(ErrorPro::getPropertyCode, property.getPropertyCode())
                            .eq(ErrorPro::getCheckId, detail.getBelongCheckId())
            ));
            if (!MyObjectUtils.isNotBlank(errorPro)){
                errorPro=new ErrorPro();
                HyCheckTask task = hyCheckTaskMapper.selectById(detail.getBelongCheckTaskId());
                errorPro.setPropertyCode(property.getPropertyCode());
                errorPro.setCheckId(detail.getBelongCheckId());
                errorPro.setTaskId(detail.getBelongCheckTaskId());
                errorPro.setMsg(detail.getDetailMsg());
                errorPro.setState(1);
                errorPro.setPhoto(detail.getPhoto());
                errorPro.setDel(1);
                errorPro.setCheckerId(task.getTaskCheckerId());
                errorPro.setFindId(currentUser.getUserId());
                errorPro.setManagerId(property.getOwnerId());
                errorPro.setManagerDeptId(property.getOwnerDeptId());
                errorPro.setUnitId(detail.getUnitId());
                errorPro.setExceptionState(StateConst.ERROR_MESSAGE_NO);
                errorPro.setPropertyName(property.getPropertyName());
                errorPro.setPlaceId(property.getPlaceId());
                errorPro.setPropertyTypeId(property.getPropertyTypeId());
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(new Date());
                errorPro.setCreateDate(format);
                errorProMapper.insert(errorPro);
            }else {
                errorPro.setExceptionState(StateConst.ERROR_LOSS_PROPERTY);
                errorPro.setMsg(detail.getDetailMsg());
                errorPro.setPhoto(detail.getPhoto());
                errorProMapper.updateById(errorPro);
            }

        }catch (Exception e){
            e.printStackTrace();
            return RespResult.put(RespResultCode.REPEATED_OPERATE);
        }


        return RespResult.success();


    }
    public RespResult detailPanKui(HyCheckDetail detail){
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        ErrorPro errorPro=null;
        HyProperty property = propertyMapper.getPropertyByUnitAndRfid(detail.getUnitId(), detail.getPropertyRfid(),detail.getBelongCheckTaskId());
        try{
            errorPro = errorProMapper.selectOne(new LambdaQueryWrapper<ErrorPro>().and(wapper ->
                    wapper.eq(ErrorPro::getPropertyCode, property.getPropertyCode())
                            .eq(ErrorPro::getCheckId, detail.getBelongCheckId())
            ));
             if (!MyObjectUtils.isNotBlank(errorPro)){
                 errorPro=new ErrorPro();
                 HyCheckTask task = hyCheckTaskMapper.selectById(detail.getBelongCheckTaskId());
                 errorPro.setPropertyCode(property.getPropertyCode());
                 errorPro.setCheckId(detail.getBelongCheckId());
                 errorPro.setTaskId(detail.getBelongCheckTaskId());
                 errorPro.setMsg(detail.getDetailMsg());
                 errorPro.setState(1);
                 errorPro.setPhoto(detail.getPhoto());
                 errorPro.setDel(1);
                 errorPro.setCheckerId(task.getTaskCheckerId());
                 errorPro.setFindId(currentUser.getUserId());
                 errorPro.setManagerId(property.getOwnerId());
                 errorPro.setManagerDeptId(property.getOwnerDeptId());
                 errorPro.setUnitId(detail.getUnitId());
                 errorPro.setExceptionState(StateConst.ERROR_LOSS_PROPERTY);
                 errorPro.setPropertyName(property.getPropertyName());
                 errorPro.setPlaceId(property.getPlaceId());
                 errorPro.setPropertyTypeId(property.getPropertyTypeId());
                 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 String format = simpleDateFormat.format(new Date());
                 errorPro.setCreateDate(format);
                 errorProMapper.insert(errorPro);
             }else {
                 errorPro.setExceptionState(StateConst.ERROR_LOSS_PROPERTY);
                 errorPro.setMsg(detail.getDetailMsg());
                 errorPro.setPhoto(detail.getPhoto());
              errorProMapper.updateById(errorPro);
             }

        }catch (Exception e){
            e.printStackTrace();
            return RespResult.put(RespResultCode.REPEATED_OPERATE);
        }


        return RespResult.success();
    }
    public RespResult detailSunHui(HyCheckDetail detail){
        try{


            HyUserVO currentUser = CommonUtils.getCurrentUser();
            ErrorPro errorPro=null;
            HyProperty property = propertyMapper.getPropertyByUnitAndRfid(detail.getUnitId(), detail.getPropertyRfid(),detail.getBelongCheckTaskId());
            HyCheckTask task = hyCheckTaskMapper.selectById(detail.getBelongCheckTaskId());
            errorPro = errorProMapper.selectOne(new LambdaQueryWrapper<ErrorPro>().and(wapper ->
                    wapper.eq(ErrorPro::getPropertyCode, property.getPropertyCode())
                            .eq(ErrorPro::getCheckId, detail.getBelongCheckId())
            ));
            if (!MyObjectUtils.isNotBlank(errorPro)){
                errorPro.setPropertyCode(property.getPropertyCode());
                errorPro.setCheckId(detail.getBelongCheckId());
                errorPro.setTaskId(detail.getBelongCheckTaskId());
                errorPro.setMsg(detail.getDetailMsg());
                errorPro.setState(1);
                errorPro.setPhoto(detail.getPhoto());
                errorPro.setDel(1);
                errorPro.setCheckerId(task.getTaskCheckerId());
                errorPro.setFindId(currentUser.getUserId());
                errorPro.setManagerId(property.getOwnerId());
                errorPro.setManagerDeptId(property.getOwnerDeptId());
                errorPro.setUnitId(detail.getUnitId());
                errorPro.setExceptionState(StateConst.ERROR_BAD_WAIT_OUT);
                errorPro.setPropertyName(property.getPropertyName());
                errorPro.setPlaceId(property.getPlaceId());
                errorPro.setPropertyTypeId(property.getPropertyTypeId());
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(new Date());
                errorPro.setCreateDate(format);
                errorProMapper.insert(errorPro);
            }else {
                errorPro.setExceptionState(StateConst.ERROR_BAD_WAIT_OUT);
                errorPro.setMsg(detail.getDetailMsg());
                errorPro.setPlaceId(detail.getHoldPlaceId());
                errorPro.setPhoto(detail.getPhoto());
                errorProMapper.updateById(errorPro);
            }

        }catch (Exception e){
            e.printStackTrace();
            return RespResult.put(RespResultCode.REPEATED_OPERATE);
        }

        return RespResult.success();
    }
    public RespResult detailXianZhi(HyCheckDetail detail){
//        HyUserVO currentUser = CommonUtils.getCurrentUser();
//        ErrorPro errorPro=new ErrorPro();
//        HyProperty property = propertyMapper.getPropertyByUnitAndRfid(detail.getUnitId(), detail.getPropertyRfid(),detail.getBelongCheckTaskId());
//        HyCheckTask task = hyCheckTaskMapper.selectById(detail.getBelongCheckTaskId());
//        errorPro.setPropertyCode(property.getPropertyCode());
//        errorPro.setCheckId(detail.getBelongCheckId());
//        errorPro.setTaskId(detail.getBelongCheckTaskId());
//        errorPro.setMsg(detail.getDetailMsg());
//        errorPro.setState(1);
//        errorPro.setPhoto(detail.getPhoto());
//        errorPro.setDel(1);
//        errorPro.setCheckerId(task.getTaskCheckerId());
//        errorPro.setFindId(currentUser.getUserId());
//        errorPro.setManagerId(property.getOwnerId());
//        errorPro.setManagerDeptId(property.getOwnerDeptId());
//        errorPro.setUnitId(detail.getUnitId());
//        errorPro.setExceptionState(StateConst.ERROR_NO_USE);
//        errorPro.setPropertyName(property.getPropertyName());
//        errorPro.setPlaceId(property.getPlaceId());
//        errorPro.setPropertyTypeId(property.getPropertyTypeId());
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String format = simpleDateFormat.format(new Date());
//        errorPro.setCreateDate(format);
//        errorProMapper.insert(errorPro);
//        return RespResult.success();
        try{


            HyUserVO currentUser = CommonUtils.getCurrentUser();
            ErrorPro errorPro=null;
            HyProperty property = propertyMapper.getPropertyByUnitAndRfid(detail.getUnitId(), detail.getPropertyRfid(),detail.getBelongCheckTaskId());
            HyCheckTask task = hyCheckTaskMapper.selectById(detail.getBelongCheckTaskId());
            errorPro = errorProMapper.selectOne(new LambdaQueryWrapper<ErrorPro>().and(wapper ->
                    wapper.eq(ErrorPro::getPropertyCode, property.getPropertyCode())
                            .eq(ErrorPro::getCheckId, detail.getBelongCheckId())
            ));
            if (!MyObjectUtils.isNotBlank(errorPro)){
                errorPro.setPropertyCode(property.getPropertyCode());
                errorPro.setCheckId(detail.getBelongCheckId());
                errorPro.setTaskId(detail.getBelongCheckTaskId());
                errorPro.setMsg(detail.getDetailMsg());
                errorPro.setState(1);
                errorPro.setPhoto(detail.getPhoto());
                errorPro.setDel(1);
                errorPro.setCheckerId(task.getTaskCheckerId());
                errorPro.setFindId(currentUser.getUserId());
                errorPro.setManagerId(property.getOwnerId());
                errorPro.setManagerDeptId(property.getOwnerDeptId());
                errorPro.setUnitId(detail.getUnitId());
                errorPro.setExceptionState(StateConst.ERROR_NO_USE);
                errorPro.setPropertyName(property.getPropertyName());
                errorPro.setPlaceId(property.getPlaceId());
                errorPro.setPropertyTypeId(property.getPropertyTypeId());
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(new Date());
                errorPro.setCreateDate(format);
                errorProMapper.insert(errorPro);
            }else {
                errorPro.setExceptionState(StateConst.ERROR_NO_USE);
                errorPro.setMsg(detail.getDetailMsg());
                errorPro.setPlaceId(detail.getHoldPlaceId());
                errorPro.setPhoto(detail.getPhoto());
                errorProMapper.updateById(errorPro);
            }

        }catch (Exception e){
            e.printStackTrace();
            return RespResult.put(RespResultCode.REPEATED_OPERATE);
        }

        return RespResult.success();
    }
    public RespResult panYing(ErrorPro errorPro){
        Optional.ofNullable(errorPro)
                .filter(MyObjectUtils::isNotBlank)
                .ifPresent(e->{
                    //修改状态为已通过
                    errorProMapper.update(null,new LambdaUpdateWrapper<ErrorPro>().eq(ErrorPro::getId,e.getId())
                            .set(ErrorPro::getState,2));
                    // 新增资产
                    HyProperty hyProperty=new HyProperty();

                    BeanUtils.copyProperties(e,hyProperty);
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = simpleDateFormat.format(new Date().getTime() + CommonConst.GMT_TIME);
                    hyProperty.setCreateDate(date);
                    hyProperty.setUpdateDate(date);
                    synchronized (RedisConst.lock){
                        hyProperty.setPropertyId(redisTemplate.opsForValue().increment(RedisConst.PROPERTY_INCREMENT_ID).intValue());
                        hyProperty.setPropertyRfid(redisTemplate.opsForValue().increment(RedisConst.UNIT_INCREMENT_RFID+e.getUnitId()).intValue());
                    }
                    hyProperty.setManagerDeptId(CommonConst.DEFAULT_ID);
                    hyProperty.setOwnerDeptId(CommonConst.DEFAULT_ID);
                    hyProperty.setManagerId(CommonConst.DEFAULT_ID);
                    hyProperty.setOwnerId(CommonConst.DEFAULT_ID);
                    hyProperty.setPropertyState((byte)1);
                    hyProperty.setOutProperty(1);
                    hyProperty.setDel(1);
                    hyProperty.setEpc(getEPC(hyProperty));
                    HyPropertySort hyPropertySort = sortMapper.selectById(hyProperty.getPropertyTypeId() == null ? CommonConst.DEFAULT_ID : hyProperty.getPropertyTypeId());
                    hyProperty.setPropertyCode(CommonUtils.getPropertyCode(hyProperty,hyPropertySort));
                    propertyMapper.insert(hyProperty);
                    //添加资产到盘点详情。
                    HyCheckDetail detail=new HyCheckDetail();
                    detail.setDel(1);
                    detail.setBelongCheckId(e.getCheckId());
                    detail.setBelongCheckTaskId(e.getTaskId());
                    detail.setCheckState(StateConst.FIND_PROPERTY);
                    detail.setPropertyRfid(hyProperty.getPropertyRfid());
                    detail.setEndDate(e.getCreateDate());
                    detail.setUnitId(e.getUnitId());
                    detail.setCheckType(2);
                    detail.setDetailMsg(e.getMsg());
                    hyCheckDetailMapper.insert(detail);
                    //给task的数量加1
                    hyCheckTaskMapper.incrementTargetField(e.getTaskId());

                });
        return RespResult.success();
    }

    public RespResult panKui(ErrorPro errorPro){

        //同意盘亏后、这个东西就应该从系统中删除掉。
        HyPropertyVO propertyByCode = propertyMapper.getPropertyByCode(errorPro.getPropertyCode());
        propertyMapper.deleteById(propertyByCode.getPropertyId());
        return RespResult.success();
    }
    public RespResult sunHui(ErrorPro errorPro){

        //同意损毁后、此物件应该更改状态为损毁待报废。
        HyPropertyVO propertyByCode = propertyMapper.getPropertyByCode(errorPro.getPropertyCode());
        propertyMapper.update(null,new LambdaUpdateWrapper<HyProperty>().eq(HyProperty::getPropertyId,propertyByCode.getPropertyId())
                .set(HyProperty::getPropertyState,CommonConst.PROPERTY_SCRAP));
        return RespResult.success();
    }
    public RespResult xianZhi(ErrorPro errorPro){

        //同意闲置后、变为闲置
        HyPropertyVO propertyByCode = propertyMapper.getPropertyByCode(errorPro.getPropertyCode());
        propertyMapper.update(null,new LambdaUpdateWrapper<HyProperty>().eq(HyProperty::getPropertyId,propertyByCode.getPropertyId())
                .set(HyProperty::getPropertyState,CommonConst.PROPERTY_IDLE));
        return RespResult.success();
    }
    public RespResult xinXiBuYiZhi(ErrorPro errorPro){

        //同意更新后、覆盖掉原来的。
        HyPropertyVO propertyByCode = propertyMapper.getPropertyByCode(errorPro.getPropertyCode());
        propertyMapper.update(null,new LambdaUpdateWrapper<HyProperty>().eq(HyProperty::getPropertyId,propertyByCode.getPropertyId())
                .set(HyProperty::getOwnerId,errorPro.getManagerId())
                .set(HyProperty::getOwnerDeptId,errorPro.getManagerDeptId())
                .set(HyProperty::getPropertyName,errorPro.getPropertyName())
                .set(HyProperty::getPropertyTypeId,errorPro.getPropertyTypeId())
                .set(HyProperty::getPlaceId,errorPro.getPlaceId()));
        return RespResult.success();
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespResult addHyCheck(CheckAddDTO addDTO) {
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        //1.先添加盘点单对象。
        HyCheck hyCheck = addDTO.getHyCheck();
        hyCheck.setCheckState(StateConst.CHECK_ING);
        hyCheck.setCreateUserId(currentUser.getUserId());
        hyCheck.setUnitId(currentUser.getUnitId());
        hyCheck.setDel(1);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date().getTime() + CommonConst.GMT_TIME);
        hyCheck.setCreateDate(format);
        hyCheckMapper.insert(hyCheck);
        //然后再从redis里拿到分类后的子任务信息、插入子任务表、盘点详情表。同时给指定盘点人设置盘点员的权限。
        for (TaskDTO hyCheckTaskCopy : addDTO.getHyCheckTasks()) {
            HyCheckTask task=new HyCheckTask();
            BeanUtils.copyProperties(hyCheckTaskCopy,task);
            List<Integer> propertyRFIDs = (List<Integer>)redisTemplate.opsForHash().get(RedisConst.TASK_PROPERTY_LIST + currentUser.getUserId(), task.getTaskId());
            task.setTaskState(StateConst.CHECK_ING);
            task.setCreateDate(format);
            task.setTaskCreateId(currentUser.getUserId());
            task.setTaskState(StateConst.CHECK_ING);
            task.setTaskId(null);
            task.setDel(1);
            task.setTaskCheckerId(hyCheck.getCheckUserId());//审核人
            task.setTaskBelongId(hyCheck.getCheckId());
            hyCheckTaskMapper.insert(task);
            Integer taskId=task.getTaskId();
            userService.addTaskUserById(task.getTaskUserId());
            propertyRFIDs.forEach( e->{
                HyCheckDetail detail=new HyCheckDetail();

                detail.setUnitId(currentUser.getUnitId());//设置单位ID
                detail.setDel(1);
                detail.setCheckState(StateConst.NO_TAKEN_STOCK);//设置盘点状态
                detail.setBelongCheckTaskId(taskId);//设置所属的子任务ID
                detail.setBelongCheckId(hyCheck.getCheckId());//设置所属的盘点单ID
                detail.setPropertyRfid(e);

                hyCheckDetailMapper.insert(detail);
            });
        }
        redisTemplate.delete(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId());
        return RespResult.getInstance(RespResultCode.Add_SUCCESS);
    }

    @Override
    public RespResult sortByDTO(CheckSortDTO sortDTO) {


        Function<CheckSortDTO, RespResult> checkSortDTORespResultFunction = sortTypeMap.get(sortDTO.getSortMode());
        if (checkSortDTORespResultFunction!=null){
            return checkSortDTORespResultFunction.apply(sortDTO);
        }
        return RespResult.error(500,"没有此分类方法！");

    }

    @Override
    public RespResult sortByManageDept(CheckSortDTO sortDTO) {
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        redisTemplate.delete(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId());
        HyPropertySearchDTO searchDTO = sortDTO.getSearchDTO();
        searchDTO.setUnitId(currentUser.getUnitId());
        searchDTO.setDel(1);
        searchDTO.setOutProperty(1);
        //拿到本次盘点的所有的资产。
        List<HyPropertyVO> propertyVOS= propertyService.listPageByDto(BeanUtil.beanToMap(searchDTO),searchDTO.getCurrentPage(),searchDTO.getPageSize());
        //根据管理人部门来分类、插入Redis。每一个子任务的资产id 、键为部门的ID、值为资产对象数组
        Map<Integer, List<HyPropertyVO>> collect = propertyVOS.stream().collect(Collectors.groupingBy(HyProperty::getManagerDeptId));
        List<TaskVO> taskVOS=new ArrayList<>();
        for (Map.Entry<Integer, List<HyPropertyVO>> integerListEntry : collect.entrySet()) {
            TaskVO taskVO=new TaskVO();
            taskVO.setTaskId(integerListEntry.getKey());
            HyDepartment department = departmentMapper.selectById(integerListEntry.getKey());
            taskVO.setTaskName(department.getDepartmentName()+"(按照管理部门分类)");
            taskVO.setTaskCount(integerListEntry.getValue().size());
            taskVOS.add(taskVO);
            List<Integer> propertyIds=new ArrayList<>();
            for (HyPropertyVO hyPropertyVO : integerListEntry.getValue()) {
                propertyIds.add(hyPropertyVO.getPropertyRfid());
            }
            redisTemplate.opsForHash().put(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId(),integerListEntry.getKey(),propertyIds);
        }


        return RespResult.success(taskVOS);
    }


    @Override
    public RespResult sortByPlace(CheckSortDTO sortDTO) {
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        redisTemplate.delete(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId());
        HyPropertySearchDTO searchDTO = sortDTO.getSearchDTO();
        searchDTO.setUnitId(currentUser.getUnitId());
        searchDTO.setDel(1);
        searchDTO.setOutProperty(1);
        //拿到本次盘点的所有的资产。
        List<HyPropertyVO> propertyVOS= propertyService.listPageByDto(BeanUtil.beanToMap(searchDTO),searchDTO.getCurrentPage(),searchDTO.getPageSize());
        //根据管理人部门来分类、插入Redis。每一个子任务的资产id 、键为部门的ID、值为资产对象数组
        Map<Integer, List<HyPropertyVO>> collect = propertyVOS.stream().collect(Collectors.groupingBy(HyProperty::getPlaceId));
        List<TaskVO> taskVOS=new ArrayList<>();
        for (Map.Entry<Integer, List<HyPropertyVO>> integerListEntry : collect.entrySet()) {
            TaskVO taskVO=new TaskVO();
            taskVO.setTaskId(integerListEntry.getKey());
            HyPlace hyPlace = placeMapper.selectById(integerListEntry.getKey());
            HyPlace hyPlace1=null;
            if (!hyPlace.getPlaceMgr().equals(1)) {
                 hyPlace1= placeMapper.selectById(hyPlace.getPlaceMgr());
            }
            taskVO.setTaskName(hyPlace1==null?hyPlace.getPlaceName()+"(按照存放区域分类)":hyPlace1.getPlaceName()+hyPlace.getPlaceName()+"(按照存放区域分类)");
            taskVO.setTaskCount(integerListEntry.getValue().size());
            taskVOS.add(taskVO);
            List<Integer> propertyIds=new ArrayList<>();
            for (HyPropertyVO hyPropertyVO : integerListEntry.getValue()) {
                propertyIds.add(hyPropertyVO.getPropertyRfid());
            }
            redisTemplate.opsForHash().put(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId(),integerListEntry.getKey(),propertyIds);
        }


        return RespResult.success(taskVOS);
    }
    @Override
    public RespResult sortByPropertySort(CheckSortDTO sortDTO) {
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        redisTemplate.delete(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId());
        HyPropertySearchDTO searchDTO = sortDTO.getSearchDTO();
        searchDTO.setDel(1);
        searchDTO.setOutProperty(1);
        //拿到本次盘点的所有的资产。
        List<HyPropertyVO> propertyVOS= propertyService.listPageByDto(BeanUtil.beanToMap(searchDTO),searchDTO.getCurrentPage(),searchDTO.getPageSize());
        //根据资产类别来分类、插入Redis。每一个子任务的资产id 、键为部门的ID、值为资产对象数组
        Map<Integer, List<HyPropertyVO>> collect = propertyVOS.stream().collect(Collectors.groupingBy(HyProperty::getPropertyTypeId));
        List<TaskVO> taskVOS=new ArrayList<>();
        for (Map.Entry<Integer, List<HyPropertyVO>> integerListEntry : collect.entrySet()) {
            TaskVO taskVO=new TaskVO();
            taskVO.setTaskId(integerListEntry.getKey());
            HyPropertySort hyPropertySort = sortMapper.selectById(integerListEntry.getKey());
            taskVO.setTaskName(hyPropertySort.getSortName()+"(按照资产类别分类)");
            taskVO.setTaskCount(integerListEntry.getValue().size());
            taskVOS.add(taskVO);
            List<Integer> propertyIds=new ArrayList<>();
            for (HyPropertyVO hyPropertyVO : integerListEntry.getValue()) {
                propertyIds.add(hyPropertyVO.getPropertyRfid());
            }
            redisTemplate.opsForHash().put(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId(),integerListEntry.getKey(),propertyIds);
        }


        return RespResult.success(taskVOS);
    }

    @Override
    public RespResult sortByManageUser(CheckSortDTO sortDTO) {
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        redisTemplate.delete(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId());
        HyPropertySearchDTO searchDTO = sortDTO.getSearchDTO();
        searchDTO.setDel(1);
        searchDTO.setOutProperty(1);
        //拿到本次盘点的所有的资产。
        List<HyPropertyVO> propertyVOS= propertyService.listPageByDto(BeanUtil.beanToMap(searchDTO),searchDTO.getCurrentPage(),searchDTO.getPageSize());
        //根据管理人来分类、插入Redis。每一个子任务的资产id 、键为部门的ID、值为资产对象数组
        Map<Integer, List<HyPropertyVO>> collect = propertyVOS.stream().collect(Collectors.groupingBy(HyProperty::getManagerId));
        List<TaskVO> taskVOS=new ArrayList<>();
        for (Map.Entry<Integer, List<HyPropertyVO>> integerListEntry : collect.entrySet()) {
            TaskVO taskVO=new TaskVO();
            taskVO.setTaskId(integerListEntry.getKey());
            HyUser hyUser = userMapper.selectById(integerListEntry.getKey());
            taskVO.setTaskName(hyUser.getUsername()+"(按照管理人分类)");
            taskVO.setTaskCount(integerListEntry.getValue().size());
            taskVOS.add(taskVO);
            List<Integer> propertyIds=new ArrayList<>();
            for (HyPropertyVO hyPropertyVO : integerListEntry.getValue()) {
                propertyIds.add(hyPropertyVO.getPropertyRfid());
            }
            redisTemplate.opsForHash().put(RedisConst.TASK_PROPERTY_LIST+currentUser.getUserId(),integerListEntry.getKey(),propertyIds);
        }


        return RespResult.success(taskVOS);
    }

    @Override
    public RespResult searchByDTO(CheckSearchDTO searchDTO) {
        searchDTO.setDel(1);
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        List<String> roles = currentUser.getRoles();
        if (CommonUtils.isMember(roles,CommonConst.SYSTEM_ROLE_NAME)){
            Page<HyCheckVO> hyCheckPage=new Page<>(searchDTO.getCurrentPage(),searchDTO.getPageSize());
            List<HyCheckVO> hyCheckVOS=   hyCheckMapper.searchByDto(hyCheckPage,searchDTO);
            return RespResult.success(hyCheckVOS).setCount(Long.valueOf(hyCheckPage.getTotal()).intValue());
        }else {
            searchDTO.setUnitID(currentUser.getUnitId());
            Page<HyCheckVO> hyCheckPage=new Page<>(searchDTO.getCurrentPage(),searchDTO.getPageSize());
            List<HyCheckVO> hyCheckVOS=   hyCheckMapper.searchByDto(hyCheckPage,searchDTO);
            return RespResult.success(hyCheckVOS).setCount(Long.valueOf(hyCheckPage.getTotal()).intValue());
        }
    }

    @Override
    public RespResult getCheckTaskById(Integer id) {

     List<HyTaskVO>  hyTaskVOS= hyCheckTaskMapper.getCheckTaskById(id);
     return RespResult.success(hyTaskVOS);
    }

    @Override
    public RespResult getDetailByTaskDetailDto(TaskDetailDTO taskDetailDTO) {
        taskDetailDTO.setDel(1);
        Page<HyCheckDetailVO> page=null;
        if (taskDetailDTO.getCurrentPage()==null||taskDetailDTO.getCurrentPage()==null){
            page=new Page<>();
        }else {
            page=new Page<>(taskDetailDTO.getCurrentPage(),taskDetailDTO.getPageSize());
        }
        List<HyCheckDetailVO> detailVOS=hyCheckDetailMapper.getDetailByTaskDetailDto(page,taskDetailDTO);


        return RespResult.success(detailVOS).setCount(Long.valueOf(page.getTotal()).intValue());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespResult checkState(CheckDTO checkDTO) {


        Integer checkTaskId = checkDTO.getCheckTaskId();
        Integer checkId = checkDTO.getCheckId();
        RespResult result=null;
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date().getTime() + CommonConst.GMT_TIME);
        if(checkTaskId!=null){
            HyCheckTask realTask = hyCheckTaskMapper.selectById(checkTaskId);
            HyCheckTask task=new HyCheckTask();
            switch (checkDTO.getState()){
                case 1:
                    result= RespResult.error(500,"错误！");
                    break;
                case 2:
                    if (realTask.getTaskState().equals(StateConst.CHECK_BACK)){
                        task.setRealOverDate(format);
                        task.setTaskId(checkTaskId);
                        task.setTaskState(checkDTO.getState());
                        hyCheckTaskMapper.updateById(task);
                        result= RespResult.success();
                    }else {
                        result= RespResult.error(500,"错误！");
                    }
                    break;
                case 3:
                    if (realTask.getTaskState()!=StateConst.CHECK_WAIT_CHECK) {
                        result= RespResult.error(500,"错误！");
                        break;
                    }
                    task.setRealOverDate(format);
                    task.setTaskId(checkTaskId);
                    task.setTaskState(checkDTO.getState());
                    hyCheckTaskMapper.updateById(task);
                    changeCheckIfAllOver(checkTaskId);
                    result= RespResult.success();
                    break;
                case 4:
                    task.setRealOverDate(format);
                    task.setTaskId(checkTaskId);
                    task.setTaskState(checkDTO.getState());
                    hyCheckTaskMapper.updateById(task);
                    result= RespResult.success();
                    break;
                case 5:
                    if (realTask.getTaskState()!=StateConst.CHECK_WAIT_CHECK) {
                       result= RespResult.error(500,"错误！");
                       break;
                    }
                    task.setTaskId(checkTaskId);
                    task.setTaskState(checkDTO.getState());
                    hyCheckTaskMapper.updateById(task);
                    result= RespResult.success();
                    break;
                default:
                    result= RespResult.error(500,"状态有误！");
            }

        }else {
            HyCheck realCheck=hyCheckMapper.selectById(checkId);
            HyCheck hyCheck=new HyCheck();
            switch (checkDTO.getState()){
                case 1:
                    result= RespResult.error(500,"错误！");
                    break;
                case 2:
                    if (realCheck.getCheckState().equals(StateConst.CHECK_BACK)){
                        hyCheck.setRealOverDate(format);
                        hyCheck.setCheckId(checkId);
                        hyCheck.setCheckState(checkDTO.getState());
                        hyCheckMapper.updateById(hyCheck);
                        result= RespResult.success();
                    }else {
                        result= RespResult.error(500,"错误！");
                    }
                    break;
                case 3:
                    if (realCheck.getCheckState()!=StateConst.CHECK_WAIT_CHECK) {
                        result= RespResult.error(500,"错误！");
                        break;
                    }
                    hyCheck.setRealOverDate(format);
                    hyCheck.setCheckId(checkId);
                    hyCheck.setCheckState(checkDTO.getState());
                    hyCheckMapper.updateById(hyCheck);
                    result= RespResult.success();
                    break;
                case 4:
                    hyCheck.setRealOverDate(format);
                    hyCheck.setCheckId(checkId);
                    hyCheck.setCheckState(checkDTO.getState());
                    hyCheckMapper.updateById(hyCheck);
                    result= RespResult.success();
                    break;
                case 5:
                    if (realCheck.getCheckState()!=StateConst.CHECK_WAIT_CHECK) {
                        result= RespResult.error(500,"错误！");
                        break;
                    }
                    hyCheck.setCheckId(checkId);
                    hyCheck.setCheckState(checkDTO.getState());
                    hyCheckMapper.updateById(hyCheck);
                    result= RespResult.success();
                    break;
                default:
                    result= RespResult.error(500,"状态有误！");
            }
        }

        return result;



    }

    @Override
    public RespResult overTask(Integer checkTaskId) {
        HyCheckTask task = hyCheckTaskMapper.selectById(checkTaskId);
        RespResult result=null;
        if (task.getTaskState().equals(StateConst.CHECK_ING)){
            HyCheckTask hyCheckTask=new HyCheckTask();
            hyCheckTask.setTaskId(checkTaskId);
            hyCheckTask.setTaskState(StateConst.CHECK_WAIT_CHECK);
            hyCheckTaskMapper.updateById(hyCheckTask);
            result=RespResult.success();
        }else {
            result=RespResult.error(500,"失败，必须要进行中的任务才能更改！");
        }

        return result;
    }

    @Override
    public RespResult checkOneByDto(CheckDetailDTO detailDTO) {
        HyCheckDetail hyCheckDetail=new HyCheckDetail();
        BeanUtils.copyProperties(detailDTO,hyCheckDetail);
       HyProperty property= propertyMapper.getPropertyByUnitAndRfid(detailDTO.getUnitId(),detailDTO.getPropertyRfid(),detailDTO.getBelongCheckTaskId());
       HyCheckDetail detail=hyCheckDetailMapper.selectByUnitAndRfid(detailDTO.getUnitId(),detailDTO.getPropertyRfid(),detailDTO.getBelongCheckTaskId());
        //1、property的holdplace等于 detail的holdplace 直接跳过。
        LambdaUpdateWrapper<HyCheckDetail> hyCheckDetailLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        hyCheckDetailLambdaUpdateWrapper.eq(HyCheckDetail::getUnitId,detailDTO.getUnitId())
                .eq(HyCheckDetail::getPropertyRfid,detailDTO.getPropertyRfid())
                .eq(HyCheckDetail::getBelongCheckTaskId,detailDTO.getBelongCheckTaskId())
                .set(HyCheckDetail::getCheckType,detailDTO.getCheckType())
                .set(HyCheckDetail::getDetailMsg,detailDTO.getDetailMsg())
                .set(HyCheckDetail::getEndDate,detailDTO.getEndDate())
                .set(HyCheckDetail::getCheckState,detailDTO.getCheckState())
                .set(HyCheckDetail::getPhoto,detailDTO.getPhoto());
            if (property.getPlaceId().equals(detail.getHoldPlaceId())){
                //2 、其他情况直接覆盖。

                hyCheckDetailLambdaUpdateWrapper .set(HyCheckDetail::getHoldPlaceId,property.getPlaceId());


            }else {
                //2 、其他情况直接覆盖。
                hyCheckDetailLambdaUpdateWrapper.set(HyCheckDetail::getHoldPlaceId,detailDTO.getHoldPlaceId());

                hyCheckDetailMapper.update(null,hyCheckDetailLambdaUpdateWrapper);
            }
        hyCheckDetailMapper.update(null,hyCheckDetailLambdaUpdateWrapper);
        detail=hyCheckDetailMapper.selectByUnitAndRfid(detailDTO.getUnitId(),detailDTO.getPropertyRfid(),detail.getBelongCheckTaskId());
        Function<HyCheckDetail, RespResult> checkSortDTORespResultFunction = detailAsync.get(detailDTO.getCheckState());
        return checkSortDTORespResultFunction.apply(detail);
    }

    @Override
    public RespResult getTaskPlace(Integer checkTaskId) {

        List<PlaceIDVO>  placeIds=hyCheckDetailMapper.selectTreeByCheckTaskId(checkTaskId);
        Set<Integer> set=new HashSet<>();
        placeIds.forEach(e->{
            set.add(e.getPlaceId());
            set.add(e.getPlaceMgr());

        });
        List<HyPlace> hyPropertySorts=new ArrayList<>();

        List<CheckPlaceTreeVO> sortTreeVOS=new ArrayList<>();
        RespResult result;
        set.forEach( e->hyPropertySorts.add(placeMapper.selectById(e)));
        Iterator<HyPlace> iterator = hyPropertySorts.iterator();
        while (iterator.hasNext()){
            HyPlace theNext = iterator.next();
            if (theNext.getPlaceMgr()==0){
                CheckPlaceTreeVO sortTreeVO=new CheckPlaceTreeVO();
                sortTreeVO.setId(theNext.getPlaceId());
                sortTreeVO.setLabel(theNext.getPlaceName());
                sortTreeVOS.add(sortTreeVO);
                iterator.remove();
            }
        }
        List<CheckPlaceTreeVO> sortTree = getSortTree(hyPropertySorts,sortTreeVOS,checkTaskId);
        result=RespResult.success(sortTree);
        return result;



    }

    @Override
    public RespResult getPropertyByEpc(String epc) {


       HyPropertyVO propertyVO= propertyMapper.getPropertyByEpc(epc);

        return RespResult.success(propertyVO);
    }

    @Override
    public RespResult getCheckTab(Integer checkId) {
         CheckTabDTO checkTabDTO=new CheckTabDTO();
        //1、查出盘点单、设置盘点单名称、状态、查出进度。
        HyCheck hyCheck = hyCheckMapper.selectById(checkId);
        CheckTab checkTab=new CheckTab();
        checkTab.setId(hyCheck.getCheckId());
        checkTab.setName(hyCheck.getCheckName());
        checkTab.setState(hyCheck.getCheckState());
        AtomicReference<Double> plan= new AtomicReference<>(0.00d);
        AtomicReference<Double> overCount= new AtomicReference<>(0.00d);
        LambdaQueryWrapper<HyCheckTask> hyCheckTaskLambdaQueryWrapper=new LambdaQueryWrapper<>();
        hyCheckTaskLambdaQueryWrapper.eq(HyCheckTask::getTaskBelongId,checkId);

        List<HyCheckTask> hyCheckTasks = hyCheckTaskMapper.selectList(hyCheckTaskLambdaQueryWrapper);
        Optional.ofNullable(hyCheckTasks)
                .filter(e-> !Integer.valueOf(e.size()).equals(0))
                .ifPresent(e->{
                    List<CheckTab> checkTabs=new ArrayList<>();
                    for (HyCheckTask task : e) {
                        if (task.getTaskState().equals(StateConst.CHECK_OVER)||task.getTaskState().equals(StateConst.CHECK_STOP)) overCount.getAndSet(overCount.get() + 1);
                        CheckTab checkTabTask=new CheckTab();
                        checkTabTask.setId(task.getTaskId());
                        checkTabTask.setName(task.getTaskName());
                        checkTabTask.setState(task.getTaskState());
                        checkTabTask.setPlan(getTaskPlan(task.getTaskId()));
                        checkTabs.add(checkTabTask);
                    }
                    plan.set(overCount.get() / hyCheckTasks.size());

                    checkTab.setPlan( new BigDecimal(plan.get()).setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue());
                    checkTabDTO.setCheckTasks(checkTabs);
                    checkTabDTO.setHyCheck(checkTab);
                });

        return RespResult.success(checkTabDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespResult addErrorPro(ErrorProAddDTO addDTO) {
        RespResult result=null;
        try{
            ErrorPro errorPro=null;

            errorPro = errorProMapper.selectOne(new LambdaQueryWrapper<ErrorPro>().and(wapper ->
                    wapper.eq(ErrorPro::getPropertyCode, addDTO.getPropertyCode())
                            .eq(ErrorPro::getCheckId, addDTO.getCheckId())));
            HyUserVO currentUser = CommonUtils.getCurrentUser();
            if (!MyObjectUtils.isNotBlank(errorPro)){
                errorPro=new ErrorPro();
                BeanUtil.copyProperties(addDTO,errorPro);

                errorPro.setDel(1);
                errorPro.setState(1);
                errorPro.setUnitId(currentUser.getUnitId());
                errorPro.setPropertyTypeId(MyObjectUtils.isNotBlank(addDTO.getPropertyTypeId())?addDTO.getPropertyTypeId():CommonConst.DEFAULT_ID);
                errorPro.setPlaceId(MyObjectUtils.isNotBlank(addDTO.getPlaceId())?addDTO.getPlaceId():CommonConst.DEFAULT_ID);
                errorPro.setManagerId(MyObjectUtils.isNotBlank(addDTO.getManagerId())?addDTO.getManagerId():CommonConst.DEFAULT_ID);
                errorPro.setManagerDeptId(MyObjectUtils.isNotBlank(addDTO.getManagerDeptId())?addDTO.getManagerDeptId():CommonConst.DEFAULT_ID);
                HyCheckTask task = hyCheckTaskMapper.selectById(errorPro.getTaskId());
                errorPro.setCheckerId(task.getTaskCheckerId());
                errorPro.setFindId(currentUser.getUserId());
                errorPro.setCreateDate(CommonUtils.getDate());
                int insert = errorProMapper.insert(errorPro);
                if (addDTO.getExceptionState().equals(StateConst.ERROR_PROPERTY)){
                    //盘盈
                    HyProperty hyProperty=new HyProperty();

                    BeanUtils.copyProperties(errorPro,hyProperty);
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = simpleDateFormat.format(new Date().getTime() + CommonConst.GMT_TIME);
                    hyProperty.setCreateDate(date);
                    hyProperty.setUpdateDate(date);
                    synchronized (RedisConst.lock){
                        hyProperty.setPropertyId(redisTemplate.opsForValue().increment(RedisConst.PROPERTY_INCREMENT_ID).intValue());
                        hyProperty.setPropertyRfid(redisTemplate.opsForValue().increment(RedisConst.UNIT_INCREMENT_RFID+errorPro.getUnitId()).intValue());
                    }

                    hyProperty.setManagerDeptId(CommonConst.DEFAULT_ID);
                    hyProperty.setOwnerDeptId(CommonConst.DEFAULT_ID);
                    hyProperty.setManagerId(CommonConst.DEFAULT_ID);
                    hyProperty.setOwnerId(CommonConst.DEFAULT_ID);
                    hyProperty.setPropertyState((byte)9);
                    hyProperty.setOutProperty(1);
                    hyProperty.setDel(1);
                    hyProperty.setEpc(getEPC(hyProperty));
                    HyPropertySort hyPropertySort = sortMapper.selectById(hyProperty.getPropertyTypeId() == null ? CommonConst.DEFAULT_ID : hyProperty.getPropertyTypeId());
                    hyProperty.setPropertyCode(CommonUtils.getPropertyCode(hyProperty,hyPropertySort));
                    propertyMapper.insert(hyProperty);
                    HyPropertyVO propertyByCode = propertyMapper.getPropertyByCode(addDTO.getPropertyCode());
                    HyCheckDetail build = HyCheckDetail.builder()
                            .belongCheckId(addDTO.getCheckId())
                            .del(1)
                            .belongCheckTaskId(addDTO.getTaskId())
                            .checkState(StateConst.FIND_PROPERTY)
                            .checkType(2)
                            .photo(addDTO.getPhoto())
                            .endDate(CommonUtils.getDate())
                            .detailMsg(addDTO.getMsg())
                            .holdPlaceId(addDTO.getPlaceId())
                            .propertyRfid(hyProperty.getPropertyRfid())
                            .unitId(hyProperty.getUnitId())
                            .build();
                    hyCheckDetailMapper.insert(build);
                    hyCheckTaskMapper.incrementTargetField(addDTO.getTaskId());

                }
                if (addDTO.getExceptionState().equals(StateConst.ERROR_MESSAGE_NO)){
                    //信息不一致
                    HyPropertyVO propertyByCode = propertyMapper.getPropertyByCode(addDTO.getPropertyCode());
                    HyCheckDetail detail = hyCheckDetailMapper.selectOne(new LambdaQueryWrapper<HyCheckDetail>().and(wapper ->
                            wapper.eq(HyCheckDetail::getUnitId, propertyByCode.getUnitId())
                                    .eq(HyCheckDetail::getPropertyRfid, propertyByCode.getPropertyRfid())
                                    .eq(HyCheckDetail::getBelongCheckId, addDTO.getCheckId())));
                    hyCheckDetailMapper.update(null,new LambdaUpdateWrapper<HyCheckDetail>().eq(HyCheckDetail::getCheckDetailId,detail.getCheckDetailId())
                            .set(HyCheckDetail::getCheckState,StateConst.Message_NO));
                }
                result=insert>0?RespResult.success():RespResult.error(500,"发生错误！");
            }else {
                //做修改
                errorPro.setPropertyName(addDTO.getPropertyName());
                errorPro.setMsg(addDTO.getMsg());
                errorPro.setPropertyTypeId(MyObjectUtils.isNotBlank(addDTO.getPropertyTypeId())?addDTO.getPropertyTypeId():CommonConst.DEFAULT_ID);
                errorPro.setPlaceId(MyObjectUtils.isNotBlank(addDTO.getPlaceId())?addDTO.getPlaceId():CommonConst.DEFAULT_ID);
                errorPro.setManagerId(MyObjectUtils.isNotBlank(addDTO.getManagerId())?addDTO.getManagerId():CommonConst.DEFAULT_ID);
                errorPro.setManagerDeptId(MyObjectUtils.isNotBlank(addDTO.getManagerDeptId())?addDTO.getManagerDeptId():CommonConst.DEFAULT_ID);
                int i = errorProMapper.updateById(errorPro);
                result=i>0?RespResult.success():RespResult.error(500,"发生错误！");
            }
        }
        catch (Exception e){
                e.printStackTrace();
                    result=RespResult.put(RespResultCode.ADD_ERROR);
                    throw new BusinessException("添加失败！");
        }
            return  result;
    }

    @Override
    public RespResult uploadPhoto(MultipartFile multipartFile, HttpServletRequest request)  {
        RespResult result=null;
        String property1 = System.getProperty("user.dir");
        String name = multipartFile.getOriginalFilename();
        String picName = UUID.randomUUID().toString() +System.currentTimeMillis()+getSuffix(name);
        if(SystemUtils.isWindows()){
            ClassPathResource classPathResource = new ClassPathResource(ExcelConstants.PHOTO_URL_PRE);
            File file= null;
            try {
                file = new File(classPathResource.getFile().getPath()+"/"+picName);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            try (InputStream inputStream = multipartFile.getInputStream()) {
                classPathResource = new ClassPathResource(ExcelConstants.PHOTO_URL_PRE+picName);
                FileOutputStream fileOutputStream=new FileOutputStream(classPathResource.getFile());
                int read;
                byte[] b = new byte[1024];
                while ((read = inputStream.read(b))!=-1) {
                    fileOutputStream.write(b);
                }
                fileOutputStream.close();
                fileOutputStream.flush();
                result=RespResult.success(ExcelConstants.PHOTO_URL_PATH+picName);
            } catch (IOException e) {
                result=RespResult.error(500,"上传失败！");
                e.printStackTrace();
            }
        }else if (SystemUtils.isLinux()){
            String property = System.getProperty("user.dir");
            URL path = ClassLoader.getSystemResource("");

            System.out.println("====================================::"+property);
            File file= null;
            try {
                File testFile=new File("/zcsystem"+ExcelConstants.PHOTO_URL_PATH);
                if (!testFile.exists()){
                    testFile.mkdir();
                }
                file = new File("/zcsystem"+"/tempPic/"+picName);
                if (!file.exists()){
                    file.createNewFile();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return RespResult.error(500,"上传失败！");
            }
            try (InputStream inputStream = multipartFile.getInputStream()) {
                FileOutputStream fileOutputStream=new FileOutputStream(file);
                int read;
                byte[] b = new byte[1024];
                while ((read = inputStream.read(b))!=-1) {
                    fileOutputStream.write(b);
                }
                fileOutputStream.close();
                fileOutputStream.flush();
                result=RespResult.success(ExcelConstants.PHOTO_URL_PATH+picName);
            } catch (IOException e) {
                result=RespResult.error(500,"上传失败！");
                e.printStackTrace();
            }
        }



        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespResult updateError(ErrorUpDateDTO upDateDTO) {

        //1. 如果传 1 那么、报错
        if (upDateDTO.getState().equals(1)) return RespResult.error(500,"错误的信号量");
        //2.如果传2 那么审核通过，判断具体的状态、则新创建盘点详情信息和资产入库。
        if (upDateDTO.getState().equals(2)){
            ErrorPro errorPro = errorProMapper.selectById(upDateDTO.getErrorId());
            Function<ErrorPro, RespResult> errorProRespResultFunction = stateMap.get(errorPro.getExceptionState());
            RespResult apply = errorProRespResultFunction.apply(errorPro);
            return apply;
        }else if (upDateDTO.getState().equals(3)){
            //3 如果传3 那么驳回审核单、审核单作废。
            errorProMapper.update(null,new LambdaUpdateWrapper<ErrorPro>().eq(ErrorPro::getId,upDateDTO.getErrorId())
                    .set(ErrorPro::getState,upDateDTO.getState()));
        }

        return RespResult.success();
    }

    @Override
    public RespResult queryByDTO(ErrorQueryDTO queryDTO) {
        Page<ErrorPro> errorProPage=queryDTO.getCurrentPage()!=null&&queryDTO.getPageSize()!=null?new Page<>(queryDTO.getCurrentPage(),queryDTO.getPageSize()):new Page<>();
       List<ErrorProVO>  errorProVOS=errorProMapper.queryByDTO(errorProPage,queryDTO);

        return RespResult.success(errorProVOS).setCount(Long.valueOf(errorProPage.getTotal()).intValue());
    }

    @Override
    public RespResult queryWaitErrorByDTO( ErrorQueryDTO queryDTO) {
        HyUserVO currentUser = CommonUtils.getCurrentUser();
        queryDTO.setCheckerId(currentUser.getUserId());
        Page<ErrorPro> errorProPage=queryDTO.getCurrentPage()!=null&&queryDTO.getPageSize()!=null?new Page<>(queryDTO.getCurrentPage(),queryDTO.getPageSize()):new Page<>();
        List<ErrorProVO>  errorProVOS=errorProMapper.queryErrorByDTO(errorProPage,queryDTO);

        return RespResult.success(errorProVOS).setCount(Long.valueOf(errorProPage.getTotal()).intValue());

    }


    private  String getEPC(HyProperty property){


        String unitId = property.getUnitId().toString();
        String propertyRfid =property.getPropertyRfid().toString();
        Integer ids=Integer.parseInt(unitId+propertyRfid);
        return ExcelUtil.Bytes2HexString(ids);

    }

    public    String getSuffix(String name){

        int i = name.lastIndexOf(".");
        return name.substring(i,name.length());


    }
    private Double getTaskPlan(Integer taskId) {
        AtomicReference<Double> plan= new AtomicReference<>(0.00d);
        AtomicReference<Double> overCount= new AtomicReference<>(0.00d);
        LambdaQueryWrapper<HyCheckDetail> hyCheckTaskLambdaQueryWrapper=new LambdaQueryWrapper<>();
        hyCheckTaskLambdaQueryWrapper.eq(HyCheckDetail::getBelongCheckTaskId,taskId);

        List<HyCheckDetail> hyCheckTasks = hyCheckDetailMapper.selectList(hyCheckTaskLambdaQueryWrapper);
        Optional.ofNullable(hyCheckTasks)
                .filter(e-> !Integer.valueOf(e.size()).equals(0))
                .ifPresent(e->{
                    for (HyCheckDetail detail : e) {
                        Integer state = detail.getCheckState();
                        if (!state.equals(StateConst.NO_TAKEN_STOCK)) overCount.getAndSet(overCount.get() + 1);
                    }
                    plan.set(overCount.get() / hyCheckTasks.size());
                });
        Double aDouble = plan.get();
        BigDecimal bigDecimal=new BigDecimal(aDouble);
        BigDecimal bigDecimal1 = bigDecimal.setScale(3, BigDecimal.ROUND_HALF_UP);
        return bigDecimal1.doubleValue();

    }

    public List<CheckPlaceTreeVO> getSortTree(List<HyPlace> sortVOS,List<CheckPlaceTreeVO> sortTreeVOS,Integer checkTaskId ){

        for (int i = 0; i < sortTreeVOS.size(); i++) {
            CheckPlaceTreeVO tree = sortTreeVOS.get(i);
            Integer id = tree.getId();
            List<CheckPlaceTreeVO> child=new ArrayList<>();
            Iterator<HyPlace> leftIt = sortVOS.iterator();
            while (leftIt.hasNext()){
                HyPlace next = leftIt.next();
                if (id.equals(next.getPlaceMgr())){
                    CheckPlaceTreeVO sortTreeVO=new CheckPlaceTreeVO();
                    sortTreeVO.setId(next.getPlaceId());
                    sortTreeVO.setLabel(next.getPlaceName());
                    TaskDetailDTO taskDetailDTO=new TaskDetailDTO();
                    taskDetailDTO.setTaskId(checkTaskId);
                    taskDetailDTO.setPropertyPlaceId(next.getPlaceId());
                    RespResult detailByTaskDetailDto = getDetailByTaskDetailDto(taskDetailDTO);
                    sortTreeVO.setOverCount(hyCheckDetailMapper.getPlaceOverCount(checkTaskId,next.getPlaceId()));
                    sortTreeVO.setPropertyCount(detailByTaskDetailDto.getCount());
                    child.add(sortTreeVO);
                    leftIt.remove();
                }
            }
            tree.setChildren(child);
        }
        return sortTreeVOS;
    }

    public void changeCheckIfAllOver(Integer checkTaskId){
        HyCheckTask task = hyCheckTaskMapper.selectById(checkTaskId);
        Integer taskBelongId = task.getTaskBelongId();
        LambdaQueryWrapper<HyCheckTask> hyCheckTaskLambdaQueryWrapper=new LambdaQueryWrapper<>();


        hyCheckTaskLambdaQueryWrapper.eq(HyCheckTask::getTaskBelongId,taskBelongId);
        List<HyCheckTask> hyCheckTasks = hyCheckTaskMapper.selectList(hyCheckTaskLambdaQueryWrapper);
        AtomicBoolean flag= new AtomicBoolean(true);
        hyCheckTasks.forEach(e->{
            if (!e.getTaskState().equals(StateConst.CHECK_OVER)&&!e.getTaskState().equals(StateConst.CHECK_STOP)){
                flag.set(false);
            }
        });

        if (flag.get()){
            HyCheck hyCheck=new HyCheck();
            hyCheck.setCheckId(task.getTaskBelongId());
            hyCheck.setCheckState(StateConst.CHECK_WAIT_CHECK);
            hyCheckMapper.updateById(hyCheck);
        }
    }

}
